#include "MatlabInterface.h"

#if defined(USE_MATLAB)
	#pragma comment( lib, "libmx"  )
	#pragma comment( lib, "libmex"  )
	#pragma comment( lib, "libmat"  )
	#pragma comment( lib, "libeng"  )
#endif

namespace matlab{

map< boost::thread::id,Engine *> MatlabInterface::eps; 				
int MatlabInterface::instances = 0; 


Engine* MatlabInterface::getEngine()
{
#ifdef USE_MATLAB

	boost::thread::id id = boost::this_thread::get_id();
	if (eps.find(id) == eps.end())
	{
		//create a new Engine for the current thread
		Engine* ep; 
		if (!(ep = engOpen("\0"))) 
//		if (!(ep = engOpen("ssh nouri@taft \"export DISPLAY=dice.rutgers.edu:0 ; matlab;\"")))
		{
			printf( "\nCan't start MATLAB engine\n");
			return 0; 
		}else
		{
			eps[id] = ep; 
			return ep; 
		}
	}else
		return eps[id]; 
#else
	return 0; 
#endif

}


MatlabInterface::MatlabInterface(void)
{
/*
#ifdef MATLAB_PLOT
	//start matlab engine if not already started
	if (instances ==0 && !ep)
	{
//		if (!(ep = engOpen("\0"))) 
		if (!(ep = engOpen("ssh nouri@taft \"export DISPLAY=dice.rutgers.edu:0 ; matlab;\"")))
		{
			printf( "\nCan't start MATLAB engine\n");
			return; 
		}
	}
	instances++; 
#endif
*/

#ifdef MATLAB_PLOT
	instances++; 
#endif
}

void MatlabInterface::closeEngines()
{
#ifdef USE_MATLAB
	for(map<boost::thread::id, Engine*>::iterator it= eps.begin(); it!= eps.end(); it++)
			engClose((*it).second);
	eps.clear(); 
	instances  = 0; 
#endif
}

MatlabInterface::~MatlabInterface(void)
{
#ifdef USE_MATLAB
	instances--; 
	return; //warning:
	closeEngines(); 
#endif
}
}
